package com.controller;

import com.util.ActiveUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("login")
public class LoginController {
    @RequestMapping("login.do")
    @ResponseBody
    public String login(String username, String password, HttpSession httpSession){
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        Subject subject= SecurityUtils.getSubject();
        try{
            subject.login(token);
            System.out.println("登录成功");
            ActiveUser activeUser=(ActiveUser) subject.getPrincipal();
            httpSession.setAttribute("user",activeUser.getUser());
            return "success";
        }catch (IncorrectCredentialsException e) {
            System.err.println("密码不正确");
        } catch (UnknownAccountException e) {
            System.err.println("用户名不存在");
        }
        return "fail";
    }
}
